package vn.fpt.fsoft.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import vn.fpt.fsoft.entity.*;
import vn.fpt.fsoft.dao.*;

import java.util.*;

/**
 * Servlet implementation class GetListTrustDistrict
 */
@WebServlet("/GetListTrustDistrict")
public class GetListTrustDistrict extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetListTrustDistrict() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String checked = request.getParameter("checked");
		String action = request.getParameter("action");
	    String filter = request.getParameter("filter");
	    Integer regionID = Integer.parseInt(request.getParameter("regionId"));
	    List<TrustDistrict> list = TrustDistrictDAO.getTrustDistrictsByRegion(regionID);
//	    
//	    if (request.getSession().getAttribute("listTrustDistrict") == null) {
//	        list = TrustDistrictDAO.getTrustDistrictsByRegion(regionID);
//	        request.getSession().setAttribute("listTrustDistrict", list);
//	    } else {
//	        list = (List<TrustDistrict>) request.getSession().getAttribute("listTrustDistrict");
//	    }   
	    
	    if("1".equals(checked)) {
	        if ("active".equals(action)) {
	            Integer id = Integer.parseInt(request.getParameter("districtID"));
                TrustDistrict trustDistrict = TrustDistrictDAO.getDistrictById(id);
                trustDistrict.setActive(true);
                TrustDistrictDAO.amendTrustDistrict(trustDistrict);
                list = TrustDistrictDAO.getTrustDistrictsByRegion(regionID);
	        }
	        if (filter != null)
	            list = filterByName(filter,list);
	    } else {
	        list = getTrustDistrictsActive(list);
	        if (filter != null)
	            list = filterByName(filter,list);
	    } 
	    if(list != null) {
	        String json = convertListToJson(list);
            response.getWriter().write(json);
	    }  
	}
	
	/**
	 * convert a list to JSON string
	 * @param list
	 * @return
	 */
	private String convertListToJson(List<TrustDistrict> list) {
		// declare a JSON object 
	    JsonObject responseDetailJson = new JsonObject();
	    // declare a JSON variable to use in loop
	    JsonObject jsonObject;
	    // declare a JSON array object to add JSON object
	    JsonArray jsonArray = new JsonArray();
	    //convert list to JSON string 
	    for(TrustDistrict tmp:list) {
	        jsonObject = new JsonObject();
	        jsonObject.addProperty("TrustDistrictId", tmp.getTrustDistrictID());
	        jsonObject.addProperty("Name", tmp.getName());
	        jsonObject.addProperty("Description", tmp.getDescription());
	        jsonObject.addProperty("RegionName", tmp.getTrustRegion().getName());
	        jsonObject.addProperty("IsActive", tmp.getActive());
	        jsonArray.add(jsonObject);
	    }
	    // add JSON array into JSON object
	    responseDetailJson.add("TrustDistricts", jsonArray);
	    return String.valueOf(responseDetailJson);
	}
	
	/**
	 * get Trust disttrict are active.
	 * @param lst
	 * @return
	 */
	private List<TrustDistrict> getTrustDistrictsActive(List<TrustDistrict> lst){
		List<TrustDistrict> list = new ArrayList<TrustDistrict>();
		for(TrustDistrict td: lst){
		    if(td.getActive()){
		        list.add(td);
		    }
		}
		return list;
	}
	
	/**
	 * filter list trust districtd on their name
	 * @param key
	 * @param list
	 * @return
	 */
	private List<TrustDistrict> filterByName(String key, List<TrustDistrict> list) {
	    List<TrustDistrict> listTmp = new ArrayList<TrustDistrict>(0);
	    char letter;
	    
	    if ("all".equals(key)) {
	       return list; 
	    } else if ("digital".equals(key)) {
	        for (TrustDistrict tmp : list) {
	            if(Character.isDigit(tmp.getName().charAt(0))) {
	                listTmp.add(tmp);
	            }
	        }
	    } else if ("ae".equals(key)) {
	        for (TrustDistrict tmp : list) {
	            letter = Character.toLowerCase(tmp.getName().charAt(0));
                if(('a' <= letter) &&  (letter <= 'e')) {
                    listTmp.add(tmp);
                }
            }
	    } else if ("fj".equals(key)) {
	        for (TrustDistrict tmp : list) {
                letter = Character.toLowerCase(tmp.getName().charAt(0));
                if(('f' <= letter) &&  (letter <= 'j')) {
                    listTmp.add(tmp);
                }
            }
	    } else if ("kn".equals(key)) {
	        for (TrustDistrict tmp : list) {
                letter = Character.toLowerCase(tmp.getName().charAt(0));
                if(('k' <= letter) &&  (letter <= 'n')) {
                    listTmp.add(tmp);
                }
            }
	    } else if ("or".equals(key)) {
	        for (TrustDistrict tmp : list) {
                letter = Character.toLowerCase(tmp.getName().charAt(0));
                if(('o' <= letter) &&  (letter <= 'r')) {
                    listTmp.add(tmp);
                }
            }
	    } else if ("sv".equals(key)) {
	        for (TrustDistrict tmp : list) {
                letter = Character.toLowerCase(tmp.getName().charAt(0));
                if(('s' <= letter) &&  (letter <= 'v')) {
                    listTmp.add(tmp);
                }
            }
	    } else if ("wz".equals(key)) {
	        for (TrustDistrict tmp : list) {
                letter = Character.toLowerCase(tmp.getName().charAt(0));
                if(('w' <= letter) &&  (letter <= 'z')) {
                    listTmp.add(tmp);
                }
            }
	    }
	    return listTmp;
	}

}
